package com.bskms.service.impl;

import java.text.SimpleDateFormat;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import com.bskms.bean.Course;
import com.bskms.bean.User;
import com.bskms.service.EmailService;

@Service
public class EmailServiceImpl implements EmailService {
    
    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
    
    @Autowired
    private JavaMailSender mailSender;
    
    private static final String FROM_EMAIL = "2872918952@qq.com";
    private static final String FROM_NAME = "幼儿园管理系统";

    @Override
    public boolean sendCourseReminderEmail(Course course, List<User> parents) {
        if (parents == null || parents.isEmpty()) {
            logger.warn("没有找到家长信息，课程ID: {}", course.getId());
            return false;
        }
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String startTime = sdf.format(course.getStart());
        
        String subject = "课程提醒 - " + course.getName();
        
        boolean allSuccess = true;
        for (User parent : parents) {
            if (parent.getUserMail() != null && !parent.getUserMail().trim().isEmpty()) {
                String childNames = null;
                try {
                    // 延迟依赖注入：通过 UserService 获取孩子姓名（按班级）
                    childNames = com.bskms.utils.SpringContext.getBean(com.bskms.service.UserService.class)
                            .getChildrenNamesByParentAndClass(parent.getUserId(), course.getClassId());
                } catch (Exception ignore) {}

                String content = buildEmailContent(course, startTime, childNames);
                boolean success = sendEmail(parent.getUserMail(), subject, content);
                if (!success) {
                    allSuccess = false;
                    logger.error("发送邮件失败，家长: {}, 邮箱: {}", parent.getUserName(), parent.getUserMail());
                } else {
                    logger.info("发送邮件成功，家长: {}, 邮箱: {}", parent.getUserName(), parent.getUserMail());
                }
            } else {
                logger.warn("家长邮箱为空，家长: {}", parent.getUserName());
            }
        }
        
        return allSuccess;
    }

    @Override
    public boolean sendEmail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(FROM_EMAIL);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            logger.error("发送邮件异常，收件人: {}, 异常: {}", to, e.getMessage(), e);
            return false;
        }
    }
    
    private String buildEmailContent(Course course, String startTime, String childNames) {
        StringBuilder content = new StringBuilder();
        content.append("亲爱的家长，您好！\n\n");
        if (childNames != null && childNames.trim().length() > 0) {
            content.append("您的孩子").append(childNames).append("所在的班级即将开始上课，具体信息如下：\n\n");
        } else {
            content.append("您的孩子所在的班级即将开始上课，具体信息如下：\n\n");
        }
        content.append("课程名称：").append(course.getName()).append("\n");
        content.append("班级：").append(course.getCname()).append("\n");
        content.append("任课老师：").append(course.getTeaName()).append("\n");
        content.append("上课时间：").append(startTime).append("\n");
        content.append("节次：第").append(course.getStep()).append("节\n");
        content.append("时段：").append(course.getAmPm() == 1 ? "上午" : "下午").append("\n\n");
        content.append("请提醒您的孩子准时上课，谢谢配合！\n\n");
        content.append("此邮件由系统自动发送，请勿回复。\n");
        content.append("幼儿园管理系统");
        
        return content.toString();
    }
}
